//
//  NSObject+QCCoding.m
//  Runtime归档
//
//  Created by QC.L on 15/12/25.
//  Copyright © 2015年 QC.L. All rights reserved.
//

#import "NSObject+QCCoding.h"
#import <objc/runtime.h>

@implementation NSObject (QCCoding)

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [self init];
    if (self) {
        // 遍例实例变量链表，逐个反归档
        unsigned int ivarCount = 0;
        Ivar *vars = class_copyIvarList(object_getClass(self), &ivarCount);
        for (int i = 0; i < ivarCount; i++) {
            Ivar var = vars[i];
            NSString *varName = [NSString stringWithUTF8String:ivar_getName(var)];
            // 反归档
            id value = [aDecoder decodeObjectForKey:varName];
            // KVC
            [self setValue:value forKey:varName];
        }
        free(vars);
    }
    return self;
}

// 遍例类中所有的实例变量，逐个进行归档、反归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
    // 遍例实例变量
    unsigned int ivarCount = 0;
    Ivar *vars = class_copyIvarList(object_getClass(self), &ivarCount);
    for (int i = 0; i < ivarCount; i++) {
        Ivar var = vars[i];
        // 获取实例变量名字
        NSString *varName = [NSString stringWithUTF8String:ivar_getName(var)];
        // KVC取值
        id value = [self valueForKey:varName];
        // 进行归档
        [aCoder encodeObject:value forKey:varName];
    }
    free(vars);
}
@end
